<template>
    <div class="session-list-panel">
        <div class="session-header">
            <h3>对话历史</h3>
            <button id="newSessionBtn" class="new-session-btn" @click="emit('sessionCreate')">
                新建会话
            </button>
        </div>
        <div id="sessionList" class="session-list">
            <div v-if="loading" style="text-align: center; padding: 20px; color: #999;">加载中...</div>
            <div v-else-if="sessions.length === 0" style="text-align: center; padding: 40px 20px; color: #999;">暂无对话历史<br>点击"新建会话"开始对话
            </div>
            <div v-else>
                <div
                        v-for="session in sessions"
                        :key="session.sessionId"
                        class="session-item"
                        :style="{ backgroundColor: currentSession?.sessionId === session.sessionId ? '#e0dfee' : 'transparent' }"
                        @click="emit('sessionSelect', session)"
                        @contextmenu.prevent="handleDeleteSession(session.id, session.title)"
                >
                    <div class="session-title">
                        {{ session.title }}
                    </div>
                    <div class="session-time">
                        {{ formatDateTime(session.updateTime) }}
                    </div>
                </div>
            </div>
        </div>
        <!-- 添加魔法特效按钮 -->
        <div class="magic-effect-section">
            <button :class="['magic-effect-btn', effectType]" @click="triggerMagicEffect">
                {{ getEffectButtonText() }}
            </button>
        </div>
        <!-- 使用魔法特效组件 -->
        <MagicEffect
                :show="showMagicEffect && effectType === 'magic'"
                :character="character"
                :duration="8000"
                @effectEnd="onMagicEffectEnd"
        />
        <!-- 使用火焰特效组件 -->
        <FireEffect
                :show="showMagicEffect && effectType === 'fire'"
                :duration="8000"
                :intensity="1.2"
                @effectEnd="onMagicEffectEnd"
        />
        <!-- 使用音符特效组件 -->
        <NodeEffect
                :show="showMagicEffect && effectType === 'node'"
                :duration="8000"
                @effectEnd="onMagicEffectEnd"
        />
    </div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {loadSessions} from '../services/sessionService';
import {getCurrentUserId} from '@/services/authService';
import {deleteSession} from '@/services/sessionService';
import MagicEffect from './MagicEffect.vue';
import FireEffect from './FireEffect.vue';
import NodeEffect from './NodeEffect.vue';

const props = defineProps({
    currentSession: {
        type: Object,
        default: null
    },
    // 添加character参数
    character: {
        type: String,
        default: ''
    }
});

const emit = defineEmits(['sessionSelect', 'sessionCreate', 'sessionDelete']);

const sessions = ref([]);
const loading = ref(true);
const userId = ref(getCurrentUserId());
// 新增：魔法特效状态
const showMagicEffect = ref(false);
// 添加一个effectType状态，用于切换不同的特效
const effectType = ref('magic'); // 可选: 'magic', 'fire', 'node'

// 根据角色更新特效类型 - 移动到使用前定义
const updateEffectTypeByCharacter = (character) => {
    // 转换为小写进行比较，避免大小写问题
    const char = character.toLowerCase();

    // 更新角色名称判断逻辑，匹配用户提供的角色名称
    if (char.includes('harry_potter') || char.includes('harry') || char.includes('哈利')) {
        effectType.value = 'magic';
    } else if (char.includes('wangye') || char.includes('王也') || char.includes('道士')) {
        effectType.value = 'fire';
    } else if (char.includes('hatsune_miku') || char.includes('miku') || char.includes('初音')) {
        effectType.value = 'node';
    } else {
        // 默认使用魔法特效
        effectType.value = 'magic';
    }
};

// 监听character变化，自动切换特效类型 - 确保在函数定义后使用
watch(() => props.character, (newCharacter) => {
    if (newCharacter) {
        updateEffectTypeByCharacter(newCharacter);
    }
}, {immediate: true});

// 触发特效的方法
const triggerMagicEffect = () => {
    showMagicEffect.value = true;
};

// 获取特效按钮的文本
const getEffectButtonText = () => {
    switch (effectType.value) {
        case 'magic':
            return '🪄 施展魔法';
        case 'fire':
            return '🔥 释放火焰';
        case 'node':
            return '🎵 奏响音符';
        default:
            return '✨ 释放技能';
    }
};

// 魔法特效结束回调
const onMagicEffectEnd = () => {
    showMagicEffect.value = false;
    // 可以在这里添加特效结束后的处理逻辑
};

// 加载会话列表 - 修改为支持角色过滤
const loadSessionList = async () => {
    try {
        loading.value = true;
        // 传递character参数给loadSessions函数
        const data = await loadSessions(userId.value, props.character);
        sessions.value = data;
    } catch (error) {
        console.error('加载会话列表失败:', error);
    } finally {
        loading.value = false;
    }
};

// 删除会话确认
const handleDeleteSession = async (sessionId, title) => {
    if (confirm(`确定要删除会话"${title}"吗？`)) {
        try {
            // 直接在组件内调用删除服务
            await deleteSession(sessionId);
            // 立即重新加载列表，确保UI及时更新
            await loadSessionList();
            // 通知父组件会话已删除
            emit('sessionDelete', sessionId);
        } catch (error) {
            console.error('删除会话失败:', error);
        }
    }
};

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
    const date = new Date(dateTimeString);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;

    return `${date.getMonth() + 1}月${date.getDate()}日`;
};

// 监听props变化，自动加载列表
watch(
    () => props.currentSession,
    () => {
        loadSessionList();
    },
    {immediate: true}
);

// 增加对character属性的监听，确保角色切换时刷新列表
watch(
    () => props.character,
    (newCharacter) => {
        if (newCharacter) {
            loadSessionList();
        }
    },
    {immediate: true}
);

// 组件挂载时加载列表
onMounted(() => {
    loadSessionList();
});
</script>

<style scoped>
.session-list-panel {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
}

.session-header {
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.session-header h3 {
    margin: 0;
    font-size: 16px; /* 减小标题字体 */
    color: #333;
}

.new-session-btn {
    padding: 6px 14px;
    background: #6c63ff;
    color: white;
    border: none;
    border-radius: 12px;
    cursor: pointer;
    font-size: 14px; /* 调整按钮字体 */
    transition: all 0.2s;
}

.new-session-btn:hover {
    background: #554eea;
    transform: translateY(-1px);
}

.session-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
}

.session-item {
    padding: 10px 12px;
    margin-bottom: 4px;
    border-radius: 12px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.session-item:hover {
    background-color: #f0f0f0;
}

.session-title {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px; /* 减小会话标题字体 */
    color: #333;
}

.session-time {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 新增：魔法特效区域样式 */
.magic-effect-section {
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    text-align: center;
}

/* 特效按钮基础样式 */
.magic-effect-btn {
    padding: 8px 16px;
    color: white;
    border: none;
    border-radius: 16px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s;
}

/* 魔法特效按钮 */
.magic-effect-btn.magic {
    background: linear-gradient(135deg, #6c63ff, #9c94ff);
    box-shadow: 0 4px 12px rgba(108, 99, 255, 0.2);
}

.magic-effect-btn.magic:hover {
    background: linear-gradient(135deg, #554eea, #8a82f0);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(108, 99, 255, 0.3);
}

/* 火焰特效按钮 */
.magic-effect-btn.fire {
    background: linear-gradient(135deg, #ff6347, #ff8c00);
    box-shadow: 0 4px 12px rgba(255, 99, 71, 0.2);
}

.magic-effect-btn.fire:hover {
    background: linear-gradient(135deg, #ff4500, #ff7f50);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(255, 99, 71, 0.3);
}

/* 音符特效按钮 */
.magic-effect-btn.node {
    background: linear-gradient(135deg, #00f2fe, #fe00fe);
    box-shadow: 0 4px 12px rgba(0, 242, 254, 0.2);
}

.magic-effect-btn.node:hover {
    background: linear-gradient(135deg, #00d8e6, #e600e6);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 242, 254, 0.3);
}

/* 特效控制区域样式 - 已移除下拉选择器，保留样式用于备用 */
.effect-controls {
    display: flex;
    gap: 12px;
    align-items: center;
    justify-content: center;
}

.effect-select {
    padding: 6px 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background: white;
    font-size: 14px;
    cursor: pointer;
    outline: none;
}

.effect-select:hover {
    border-color: #6c63ff;
}
</style>
